# coding: utf-8

import json
import mimetypes
import os
import time
import uuid
from copy import deepcopy

import pandas as pd
from flask import make_response
from flask import request, redirect, url_for

import fralog.FraLog
from dbproxy.dbproxy import *
from login.LoginFunc import check_token
from result import g_ret
from settings import app, mongo, verify_token, get_param

# 根据题干描述、题目类型单选多选、所属客户,查询客户题目
# 修改保存客户题目

log = fralog.FraLog.getFileLog()


class CustomerQuestion(object):
    """
    客户题库相关操作的接口功能均封装在此
    """
    table_name = 'questions_collection'

    def __init__(self):
        super(CustomerQuestion, self).__init__()
        self.db_proxy = DBProxy(db=mongo)

    def query_all_questions_by(self, param, company_id, type,question_type, question_title, pagesize=500, page=1):
        """
        查询所有的题目
        :param company_id: 
        :param pagesize
        :param page
        :return: 
        """
        log.debug('查询公司个性题库')
        companyret = self.get_company(param)
        companyret = companyret['data']
        company_idlist = []
        for item in companyret:
            company_idlist.append(item.get('company_name'))
        query = {}
        if question_title is not None and question_title != '':
            query['question_title'] = {'$regex': question_title}
        if type is not None and type != '':
            query['type'] = type
        if question_type is not None and (question_type == 1 or question_type == 0):
            query['question_type'] = {'$lte': 1}
        else:
            query['question_type'] = question_type
        sort = [("question_id", pymongo.DESCENDING)]
        if company_id is None or company_id == '':
            query['company_id'] = {'$in': company_idlist}
            ret = self.db_proxy.page_query(table=self.table_name, query=query, sort=sort,  # query={'company_id': {'$in': company_idlist}},
                                           page=page, pagesize=pagesize)
        else:
            if company_id is not None and company_id != '':
                query['company_id'] = company_id

            ret = self.db_proxy.page_query(table=self.table_name, query=query, sort=sort,   # {'company_id': company_id},
                                           page=page, pagesize=pagesize)
        log.debug('查询公司个性题库成功返回')
        return ret

    def query_question_detail(self, question_id):
        log.debug('查询题目明细: %s' % (question_id))
        ret = self.db_proxy.query_one(table=self.table_name, query={'question_id': int(question_id)})
        log.debug('题目明细查询结束')
        return ret

    def question_edit(self, question_id, setvalue, insert_not_found=False):
        log.debug('编辑题目')
        if setvalue.get('label') is not None:
            del setvalue['label']
        ret = self.db_proxy.update(table=self.table_name, query={'question_id': int(question_id)}, setvalue=setvalue,
                                   insert_not_found=insert_not_found)
        return ret

    def question_insert(self, setvalue):
        log.debug('新增题目')
        # setvalue['question_id'] = int(setvalue['question_id'])
        setvalue['question_type'] = int(setvalue['question_type'])

        setvalue['required'] = '是'
        if setvalue.get('label') is not None:
            del setvalue['label']
        des = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
               'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
               'W', 'X', 'Y', 'Z']
        for de in des:
            if setvalue.get(de) is None:
                setvalue[de] = None
       
        lastItem = self.db_proxy.query_lastone(table=self.table_name, field="question_id")
        print(lastItem)
        if len(lastItem['data']) > 0:
            setvalue["question_id"] = int(lastItem['data'][0]["question_id"]) + 1
        else:
            setvalue["question_id"] = 1
        ret = self.db_proxy.insert(table=self.table_name,  value=setvalue)
        return ret

    def question_delete(self, question_id):
        log.debug('删除题目: %s' % (question_id))
        question_id = int(question_id)
        ret = self.db_proxy.delete(table=self.table_name, query={'question_id': int(question_id)})
        return ret

    def question_find_query(self, param, title, type, company_id, question_type, page, pagesize):
        log.debug('选择查询公司个性题库')
        if title is None:
            title = ''
        if company_id is None:
            company_id = ''
        companyret = self.get_company(param)
        companyret = companyret['data']
        company_idlist = []
        for item in companyret:
            company_idlist.append(item.get('company_name'))
        if company_id is None or company_id == '':
            if type is None or type == '':
                ret = self.db_proxy.page_query(table=self.table_name, query={
                    'question_type': question_type,
                    'question_title': {'$regex': title},
                    'company_id': {'$in': company_idlist}
                }, page=page, pagesize=pagesize)
            else:
                ret = self.db_proxy.page_query(table=self.table_name, query={
                    'question_type': question_type,
                    'type': type,
                    'question_title': {'$regex': title},
                    'company_id': {'$in': company_idlist}
                }, page=page, pagesize=pagesize)
        else:
            if type is None or type == '':
                ret = self.db_proxy.page_query(table=self.table_name, query={
                    'question_type': question_type,
                    'question_title': {'$regex': title},
                    'company_id': company_id
                }, page=page, pagesize=pagesize)
            else:
                ret = self.db_proxy.page_query(table=self.table_name, query={
                    'question_type': question_type,
                    'type': type,
                    'question_title': {'$regex': title},
                    'company_id': company_id
                }, page=page, pagesize=pagesize)

        log.debug('选择查询公司个性题库成功返回')
        print(ret)
        return ret

    def get_company(self, param):
        '''
        查询公司列表
        :param param:
        :return:
        '''
        # log.debug('')
        post_data = param
        token = post_data.get('token')
        ret = deepcopy(g_ret)
        g_user_id, backret = check_token(token)
        if g_user_id is None:
            return backret
        page = 1
        pagesize = 0
        try:
            page = int(page)
            pagesize = int(pagesize)
        except Exception as e:
            log.info(e)
        queryret = self.db_proxy.query_one(table='t_user', query={'user_id': g_user_id})
        query = queryret.get('data')[0]
        dbret = dict()
        if query is not None:
            if query.get('role_id') == 'admin_bd' or query.get('role_id') == 'admin':
                dbret = self.db_proxy.page_query(table='company_collection', query={},
                                                 page=page, pagesize=pagesize)
            else:
                dbret = self.db_proxy.page_query(table='company_collection', query={'bd': g_user_id}, page=page,
                                                 pagesize=pagesize)
        # 验证用户提供的登录信息是否合法
        if dbret is None:
            dbret['code'] = 402
            dbret['msg'] = '无法查找到列表'
            log.info('查找为空')
            return dbret
        else:
            dbret['code'] = 200
            dbret['msg'] = '处理成功'
            dbret['msg_flag'] = 'ok'
            return dbret


customer_question = CustomerQuestion()


@app.route('/cq/query_all_questions_by', methods=['GET', 'POST'])
@verify_token
def cq_query_all_questions_by():
    '''
    查询用户题库 根据company_id 或 自动根据角色bd查询
    输入(token默认输入):company_id ,page ,pagesize ;其中company_id可不填
    返回:ret集合,ret.code=200,ret.data=[]
    :return:
    '''
    # question_typ question_title
    param = get_param(request)
    company_id = param.get('company_id')
    question_title = param.get('question_title')
    type = param.get('question_type')
    question_type = 2
    if company_id == '':
        company_id = None
    page = param.get('page')
    if page is None:
        page = 1
    else:
        page = int(page)
    pagesize = param.get('pagesize')
    if pagesize is None:
        pagesize = 0
    else:
        pagesize = int(pagesize)
    log.info('公司ID：%s' % (company_id))
    return json.dumps(
        customer_question.query_all_questions_by(param, company_id=company_id, type=type, question_type=question_type,
                                                 question_title=question_title, pagesize=pagesize, page=page))


@app.route('/cq/query_question_detail', methods=['GET', 'POST'])
@verify_token
def cq_query_question_detail():
    '''
    查询题目
    输入(token默认输入):question_id
    返回:ret集合,ret.code=200,ret.data=[]
    :return:
    '''
    param = get_param(request)
    question_id = param.get('question_id')
    log.debug('问题ID: %s' % (question_id))
    return json.dumps(customer_question.query_question_detail(question_id))


@app.route('/cq/question_edit', methods=['POST', 'GET'])
@verify_token
def cq_question_edit():
    '''
    编辑题目
    输入(token默认输入):question_id
    返回:ret集合,ret.code=200,ret.data=[]
    :return:
    '''
    param = get_param(request)
    log.debug('问题编辑')
    question_id = int(param['companyInfo']['question_id'])
    del param['token']
    log.debug('参数成功获取，准备编辑')
    return json.dumps(customer_question.question_edit(question_id=question_id, setvalue=param['companyInfo']))


@app.route('/cq/question_insert', methods=['POST', 'GET'])
@verify_token
def cq_question_insert():
    '''
    新增题目
    输入(token默认输入):question_id
    返回:ret集合,ret.code=200,ret.data=[]
    :return:
    '''
    param = get_param(request)
    log.debug('问题新增')
    data = param.get('companyInfo')
    # question_id = param.get('question_id')
    current_time = time.localtime(time.time())
    timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    data['create_time'] = timestr
    log.debug('参数成功获取，准备新增')
    return json.dumps(customer_question.question_insert(setvalue=data))


@app.route('/cq/question_delete', methods=['GET',  'POST'])
@verify_token
def cq_question_delete():
    '''
    删除题目
    输入(token默认输入):question_id
    返回:ret集合,ret.code=200,ret.data=[]
    :return:
    '''
    param = get_param(request)
    log.debug('删除题目')
    question_id = param.get('question_id')
    log.debug('题目编号: %s' % question_id)
    return json.dumps(customer_question.question_edit(question_id=question_id, setvalue={'question_type': 99}))
    # return json.dumps(customer_question.question_delete(question_id))


@app.route('/cq/question_find_query', methods=['GET', 'POST'])
@verify_token
def cq_question_find_query():
    '''
    根据  title, type, company_id, question_type 查询或者缺省根据角色查询题目
    输入(token默认输入): type page pagesize company_id
    返回:ret集合,ret.code=200,ret.data=[]
    :return:
    '''
    log.debug('选择查询客户题库')
    param = get_param(request)
    g_user_id, ret = check_token(param.get('token'))
    if g_user_id is None:
        return ret
    type = param.get('type')
    company_id = param.get('company_id')
    page = int((1 if param.get('page')is None else param.get('page')))
    pagesize = int((1000 if param.get('pagesize')is None else param.get('pagesize')))
    title = param.get('title')
    question_type = 2
    return json.dumps(customer_question.question_find_query(param, title, type, company_id, question_type, page, pagesize))


@app.route('/cq/get_company', methods=['GET', 'POST'])
@verify_token
def cq_get_company():
    '''
    查询本用公司列表,如果角色admin_bd则全部公司列表
    输入(token默认输入):page pagesize
    返回:ret集合,ret.code=200,ret.data=[]
    :return:
    '''
    log.debug('查询公司列表')
    param = get_param(request)
    return json.dumps(customer_question.get_company(param))


@app.route('/cq/test', methods=['GET', 'POST'])
def cq_test():
    log.debug('测试/cq/test')
    print('chaxun')
    param = {'test': 'ok'}
    rts = [param]
    df = pd.DataFrame(rts)
    uuidfilename = './static/'+str(uuid.uuid4()) + '.xlsx'
    df.to_excel(uuidfilename)
    # df.to_excel(uuidfilename)  # float_format 控制精度
    filename = 'lining.xlsx'
    fs = open(uuidfilename, 'rb')
    response = make_response(fs.read())
    mime_type = mimetypes.guess_type(filename)[0]
    response.headers['Content-Type'] = mime_type
    response.headers['Content-Disposition'] = 'attachment; filename={}'.format(filename.encode().decode('latin-1'))
    fs.close()
    os.remove(uuidfilename)
    return response


@app.route('/test_test_tupload', methods=['POST', 'GET'])
def test_tupload():
    if request.method == 'POST':
        f = request.files['file']
        basepath = os.path.dirname(__file__)  # 当前文件所在路径
        f.filename = str(f.filename).replace('..', '')
        upload_path = os.path.join(basepath, 'static\\', f.filename)
        f.save(upload_path)
        return redirect(url_for('upload'))
    return ''
